package org.jeecg.modules.util;

import com.alibaba.fastjson.JSON;
import org.codehaus.jettison.json.JSONArray;
import org.codehaus.jettison.json.JSONObject;
import org.codehaus.jettison.json.JSONTokener;
import org.jeecg.modules.device.Device;
import org.jeecg.modules.entity.TigDevice;

import java.util.Calendar;

public class ConvertUtil {

    public static JSONObject toJsonTigDevice(TigDevice device) throws Exception{
        JSONObject jo=null;
        try{
            jo =  new JSONObject(new JSONTokener(device.getShadowName()));
//                        JsonParser.parseString(devices.get(i).getShadowName()).getAsJsonObject();
        }catch (Exception e){
            e.printStackTrace();
        }
        if(jo == null){
            jo = new JSONObject();
        }
        jo.put("id",device.getId());
        jo.put("timestamp", Calendar.getInstance().getTime().getTime());

 //       JSONObject switches = jo.getJSONObject("switches");
        JSONObject networkJson = jo.getJSONObject("network");
        JSONObject baseinfoJson  = jo.getJSONObject("baseinfo");


        networkJson.put("ip",device.getIpAddr());
        networkJson.put("port",device.getPort());

        baseinfoJson.put("name",device.getName());
        baseinfoJson.put("isActive",device.getIson());
        if(device.getOnStatus() == null)
            baseinfoJson.put("isOnline","0");
        else
            baseinfoJson.put("isOnline",device.getOnStatus());

//        int total = switches.getInt("total");
//        JSONArray sws = switches.getJSONArray("switches");
//        JSONObject sw = sws.getJSONObject(0);
//        JSONArray newSws = new JSONArray();
//        for(int i=0;i<total;i++){
//            JSONObject a = new JSONObject(new JSONTokener(sw.toString()));
//            //a.put("name", i+"");
//            newSws.put(a);
//        }

//        switches.put("switches", newSws);
//        jo.put("switches",switches);
        jo.put("baseinfo",baseinfoJson);
        jo.put("network", networkJson);


        if(device.getOnTime() != null)
            jo.put("onTime",device.getOnTime().getTime());
        else
            jo.put("onTime",0);
        if(device.getOffTime() != null)
            jo.put("offTime",device.getOffTime().getTime());
        else
            jo.put("offTime",0);
        return jo;
    }

    public static String toSwitchState(String state) {
        if (state.compareTo("0") == 0)
            return "开";
        else
            return "关";
    }

    public static String toOnlineState(int state) {
        if (state == 0)
            return "下线";
        else
            return "在线";
    }

    public static String toActiveState(int state) {
        if (state == 0)
            return "未激活";
        else
            return "激活";
    }
}
